//
//  JBWHomeViewController.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/6/28.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit
import YYModel

//cell重用标识
private let homeCellID = "homeCellID"
class JBWHomeViewController: JBWBaseViewController {

    //创建全局的viewModel
    fileprivate lazy var homeViewModel: JBWHomeViewModel = JBWHomeViewModel()
        
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin {
            visitorView?.setupVisitorViewInfo(imgName: nil, title: nil)
            return
        }
        
        setupUI()
        //请求数据
       loadData()
    }

    
    //设置tableView
    private func setTableViewInfo(){
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(JBWHomeCell.self, forCellReuseIdentifier: homeCellID)
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 300
        //分割线样式
        tableView.separatorStyle = .none
        //设置footerView
        tableView.tableFooterView = footerView
        //添加系统刷新控件
        tableView.addSubview(refreshControl)
    }
    
    //setupUI
    private func setupUI(){
        navigationController?.view.insertSubview(pulldownTipLabel, belowSubview: (navigationController?.navigationBar)!)
        setupNav()
        setTableViewInfo()
    }
    //导航
    private func setupNav(){
        
        //左按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", title: nil, target: self, action: #selector(leftButtonClick))
        //右按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(rightButtonClick))
    }
    
    //懒加载上拉加载更多控件
    fileprivate lazy var footerView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        //颜色
        view.color = JBWThemeColor
        return view
    }()
    
    //系统下拉刷新控件
    fileprivate lazy var refreshControl: HMRefreshControl = {
        let view = HMRefreshControl()
        //监听事件
        view.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
        return view
    }()
    
    //刷新微博提示label
    fileprivate lazy var pulldownTipLabel: UILabel = {
        let lab = UILabel(frame: CGRect(x: 0, y: 64 - 30, width: JBWSCREENW, height: 30))
        lab.backgroundColor = JBWThemeColor
        lab.font = UIFont.systemFont(ofSize: JBWNormalFontSize)
        lab.textColor = UIColor.white
        lab.textAlignment = .center
        lab.isHidden = true
        return lab
    }()
    
}

/*
//请求首页数据
extension JBWHomeViewController {
    func getHomeData(){
        //请求地址
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //请求参数
        let params = ["access_token": JBWOAuthViewModel.share.accessToken]
        //发送请求
        JBWNetworkTools.share.request(type: JBWNetworkToolsType.get, urlString: urlString, parameters: params, success: { (response) in
            //判断是否为nil 及是否是一个字典
            guard let resDict = response as? [String: Any] else {
                return
            }
            
            //判断resdict 的 "ststuses" 是否为nil
            guard let resList = resDict["ststuses"] as? [String: Any] else {
                return
            }
            let temList = NSArray.yy_modelArray(with: JBWHomeModel.self, json: resList)
            
            //判断是否为nil 及是否是一个有模型的数组
            guard let t = temList as? [JBWHomeModel] else {
                return
            }
            //赋值
            self.dataList = t
            self.tableView.reloadData()
        }) { (error) in
            print("请求失败",error)
        }
        
            
    }
}
*/


/*
// 请求首页数据
extension JBWHomeViewController{
    func getHomeData(){
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = ["access_token": JBWOAuthViewModel.share.accessToken]
        // 发送请求
        JBWNetworkTools.share.request(type: JBWNetworkToolsType.get, urlString: urlString, parameters: params, success: { (response) in
            //            print("请求成功",response)
            // 判断它是否为nil 而且是否是一个字典
            guard let resDict = response as? [String: Any] else{
                return
            }
            
            // 判断resDict["statuses"] 是否为nil 而且是否是一个[[string:any]]
            guard let resList = resDict["statuses"] as? [[String: Any]] else{
                return
            }
            let tempList = NSArray.yy_modelArray(with: JBWHomeModel.self, json: resList)
            
            // 判断是否为nil 而且是否是一个有模型的数组
            guard let t = tempList as? [JBWHomeModel] else{
                return
            }
            // 赋值
            self.dataList = t
            self.tableView.reloadData()
        }) { (error) in
            print("请求失败",error)
        }
    }
}

*/

//请求首页数据
extension JBWHomeViewController {
    func loadData(){
        
        homeViewModel.getHomeData(isPullUp: self.footerView.isAnimating) { (isFinish, count) in
//            self.footerView.stopAnimating()
//            self.endRefreshing()
            //判断
            if !isFinish {
                print("请求失败")
                return
            } else {
                //判断是否是首次请求数据 或者是下拉刷新
                if !self.footerView.isAnimating {
                    self.setupPulldownTipLabelAnim(count: count)
                }
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
        
    }
    
    //设置pulldownTipLabel的动画  只在第一次和下拉刷新中设置动画
    fileprivate func setupPulldownTipLabelAnim(count: Int){
        
        //判断是否显示
        if !self.pulldownTipLabel.isHidden {
            return
        }
        
        self.pulldownTipLabel.isHidden = false
        
        //记录描述文字
        let text: String
        if count > 0 {
            text = "您已更新了\(count)条微博"
        } else {
            text = "已经是最新微博啦"
        }
        //赋值
        pulldownTipLabel.text = text
        
        //设置动画
        UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
            self.pulldownTipLabel.transform = CGAffineTransform(translationX: 0, y: 30)
        }) { (_) in
            UIView.animate(withDuration: 1, animations: { 
                self.pulldownTipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                //隐藏
                self.pulldownTipLabel.isHidden = true
            })
        }
        
    }
    
    //监听下拉舒心开始请求数据
    @objc fileprivate func refreshAction(){
        print("刷新数据")
        loadData()
    }
    
    fileprivate func endRefreshing(){
        //停止动画
        self.footerView.stopAnimating()
        self.refreshControl.endRefreshing()
    }
}

//数据源方法
extension JBWHomeViewController: UITableViewDataSource ,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellID, for: indexPath) as! JBWHomeCell
        
        //赋值
        cell.statusViewModel = homeViewModel.dataList[indexPath.row]
        //关闭cell选中效果
        cell.selectionStyle = .none
        return cell
        
        
    }
    
    //将要显示的cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //如果到最后一行 就要来气footerView的动画
        if indexPath.row == homeViewModel.dataList.count - 1 && !self.footerView.isAnimating {
            print(indexPath.row,"行数")
            //执行动画
            self.footerView.startAnimating()
            //发送网络请求
            loadData()
        }
    }
}

//监听事件
extension JBWHomeViewController {
    

    @objc func leftButtonClick(){
    print("左按钮点击")
    }

    @objc func rightButtonClick(){
    print("右按钮点击")
    
    let tempVC = JBWTempViewController()
    
    navigationController?.pushViewController(tempVC, animated: true)
    
}
}
